package com.mugui.spring.net.forward;

import java.util.HashMap;
import java.util.LinkedList;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import com.mugui.spring.base.Task;
import com.mugui.spring.base.TaskInterface;
import com.mugui.spring.net.auto.AutoTask;
import com.mugui.spring.net.bean.NetBag;
import com.mugui.spring.util.HTTPUtil;
import com.mugui.util.Other;

import cn.hutool.core.codec.Base64;

@AutoTask
@Task(blank = 60000, time = 1000, value = Task.CYCLE)
@Component
public class ForwardTask implements TaskInterface {
	private LinkedList<ForwardBean> LinkedList = new LinkedList<>();

	public void init() {
		System.out.println(ForwardTask.class.getName() + "初始化");
	}

	private HashMap<String, String> sessions = new HashMap<>();

	@Override
	public void run() {
		synchronized (LinkedList) {
			if (LinkedList.isEmpty()) {
				return;
			}
			for (ForwardBean forwardBean : LinkedList) {
				HashMap<String, String> map = new HashMap<String, String>();
				String ForwardSession = sessions.get(forwardBean.get().getString("server_url"));
				if (StringUtils.isNotBlank(ForwardSession))
					map.put("Cookie", "SESSION=" + Base64.encode(ForwardSession) + "");

				NetBag netBag = new NetBag();
				netBag.setFunc("&forward.insert.New");
				netBag.setData(forwardBean);
				netBag.setHash(Other.MD5(netBag.toString() + System.currentTimeMillis()));
				String post = HTTPUtil.post(forwardBean.get().getString("server_url"), map, netBag.toString());
				NetBag newBean = NetBag.newBean(NetBag.class, post);
				sessions.put(forwardBean.get().getString("server_url"), newBean.getSession());
				System.out.println(newBean.toString());
			}
		}
	}

	public void insert(ForwardBean forwardBean) {
		synchronized (LinkedList) {
			LinkedList.add(forwardBean);
		}
	}

}
